﻿using CPlatePrintSys.Server.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CPlatePrintSys.Server.App_Start
{
    /// <summary>
    /// 初始化管理员系统初始账号
    /// </summary>
    public class AccountInitializeConfig
    {
        public static void createAccounts()
        {
            using (var context = new ApplicationDbContext())
            {
                // 确保数据库已创建
                context.Database.Initialize(false);

                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
                var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

                // 创建角色
                CreateRoleIfNotExists(roleManager, "SuperAdmin");
                CreateRoleIfNotExists(roleManager, "User");

                // 创建管理员用户
                CreateUserIfNotExists(
                    userManager,
                    "admin",
                    "admin@jari.cn",
                    "Jarisoft@716**",
                    "系统管理员",
                    null,
                    "SuperAdmin");
            }
        }

        private static void CreateRoleIfNotExists(RoleManager<IdentityRole> roleManager, string roleName)
        {
            if (!roleManager.RoleExists(roleName))
            {
                var role = new IdentityRole { Name = roleName };
                roleManager.Create(role);
            }
        }

        private static void CreateUserIfNotExists(
            UserManager<ApplicationUser> userManager,
            string username,
            string email,
            string password,
            string fullName,
            string phoneNumber,
            params string[] roles)
        {
            var user = userManager.FindByEmail(email);
            if (user == null)
            {
                user = new ApplicationUser
                {
                    UserName = username,
                    Email = email,
                    EmailConfirmed = true,
                    FullName = fullName,
                    PhoneNumber = phoneNumber,
                    PhoneNumberConfirmed = true
                };

                var result = userManager.Create(user, password);
                if (result.Succeeded)
                {
                    foreach (var role in roles)
                    {
                        userManager.AddToRole(user.Id, role);
                    }
                }
            }
        }
    }
}